import React, { useRef } from 'react';
import Slider from 'react-slick';
import { X } from 'lucide-react';

import './styleSlider.css';

import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';

import { SliderGalleryArrow } from './SliderGalleryArrow';

export const SliderGallery = ({
  files,
  setOpen,
  activeSliderIndex = 0
}: {
  files: TaskFile[];
  setOpen: (open: boolean) => void;
  activeSliderIndex?: number;
}) => {
  const settings = {
    customPaging: function (i: number) {
      return (
        <div className='size-16 overflow-hidden'>
          <img
            src={files[i].type === 'img' ? files[i].small : files[i].icon}
            className='m-auto h-full w-full object-cover'
          />
        </div>
      );
    },
    appendDots: (dots: React.ReactNode) => (
      <div className='mt-4'>
        <ul> {dots} </ul>
      </div>
    ),
    dotsClass: 'slick-dots slick-thumb -mb-12 ',
    dots: true,
    infinite: true,
    fade: files.length > 1 ? false : true,
    speed: 400,
    slidesToShow: 1,
    slidesToScroll: 1,
    nextArrow: <SliderGalleryArrow />,
    prevArrow: <SliderGalleryArrow />,
    initialSlide: activeSliderIndex
  };

  const refer = useRef<HTMLDivElement | null>(null);

  return (
    <div
      className='absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(0,0,0,.7)] backdrop-blur-sm'
      onClick={(e) => e.stopPropagation()}
    >
      <button className='absolute right-4 top-4 border' onClick={() => setOpen(false)}>
        <X className='text-white' size={28} />
      </button>
      <Slider waitForAnimate={true} {...settings} className='m-auto flex w-[90vw] items-center' >
        {files.map(({ icon, type, url, small, medium }) => {
          return (
            <div
              key={type === 'img' ? small : icon}
              ref={refer}
              className='slickSlideStyle flex h-[80vh] w-[100%] flex-col items-center justify-center text-5xl'
            >
              <img
                onLoad={(e) => {
                  const resize = refer.current
                    ? (e.currentTarget.naturalWidth / e.currentTarget.naturalHeight) *
                    refer.current.clientHeight
                    : 100;
                  e.currentTarget.setAttribute('width', `${resize}px`);
                }}
                loading='lazy'
                src={type === 'img' ? medium : icon}
                width={451}
                className=' m-auto max-h-full max-w-full '
              />
              {type != 'img' && (
                <a href={url} target='_blank' rel='noreferrer' className='text-xl text-blue-500'>
                  {url}
                </a>
              )}
            </div>
          );
        })}
      </Slider>
    </div>
  );
};
